package com.ibl.rover.lite.client.Activity;

import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Application.OrderBookingLine;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.AppSetupBean;
import com.ibl.rover.lite.common.bean.CustomerBean;
import com.ibl.rover.lite.common.bean.OrderBean;
import com.ibl.rover.lite.common.bean.ProductBean;
import com.ibl.rover.lite.common.bean.ProductOrderBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OrderDetailActivity extends Activity implements OnClickListener {

	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;
	private CustomerBean customerBean;
	private OrderBookingLine orderBookingLine;
	private AppSetupBean appSetupBean;
	private Spinner salesTypeSpinner;

	int orderNumber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sales_order_detail);
		initialize();
	}

	/**
	 * Initialize Resources
	 */
	private void initialize() {
		try {
			roverApp = (ApplicationContext) getApplication();
			manager = roverApp.getDatabaseManager();

			customerBean = (CustomerBean) roverApp.getViewContext().get(
					RoverConstants.CURRENT_CUSTOMER);

			appSetupBean = getAppSetupBean();
			if (!roverApp.getViewContext().containsKey(
					RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS)) {
				orderNumber = (Integer.parseInt(appSetupBean.getLastOrder())) + 1;
			} else {
				OrderBean orderBean = (OrderBean) roverApp.getViewContext()
						.get(RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS);
				orderNumber = Integer.parseInt(orderBean.getOrderId());

			}
			orderBookingLine = (OrderBookingLine) roverApp.getViewContext()
					.get(RoverConstants.CURRENT_ORDER_BOOKING_LINE);

			((TextView) findViewById(R.id.txt_date))
					.setText(returnOrderCurrentDate());

			((TextView) findViewById(R.id.txt_order_no)).setText(String
					.valueOf(orderNumber));

			((TextView) findViewById(R.id.txt_customer_name))
					.setText(customerBean.getName());

			((TextView) findViewById(R.id.txt_customer_code))
					.setText(customerBean.getCode());

			((TextView) findViewById(R.id.txt_discount)).setText("0.0");

			((TextView) findViewById(R.id.txt_tax)).setText("0.0");

			((TextView) findViewById(R.id.txt_gross_amount))
					.setText(orderBookingLine.getOrderAmount());

			((TextView) findViewById(R.id.txt_net_amount))
					.setText(orderBookingLine.getOrderAmount());

			// ((TextView) findViewById(R.id.txt_tso_code_value))
			// .setText(orderBookingLine.getOrderAmount());

			salesTypeSpinner = (Spinner) findViewById(R.id.sales_type_spinner);

			ArrayAdapter<CharSequence> routeAdapter = ArrayAdapter
					.createFromResource(this, R.array.slaes_type_filter,
							android.R.layout.simple_spinner_item);

			routeAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			salesTypeSpinner.setAdapter(routeAdapter);

			((Button) findViewById(R.id.order_detail_save_btn))
					.setOnClickListener(this);
			((Button) findViewById(R.id.order_detail_save_cancel))
					.setOnClickListener(this);

		} catch (Exception e) {

			logger.logException("Initialize Exception :", e);
		}
	}

	/**
	 * Get AppSetup Bean
	 */
	private AppSetupBean getAppSetupBean() {
		try {
			List<AppSetupBean> appSetupBeanList = manager
					.findAllBean(AppSetupBean.class);
			return appSetupBeanList.get(0);
		} catch (Exception e) {
			logger.logException("GetOrderNumber ", e);
		}
		return null;
	}

	private String returnOrderCurrentDate() {
		try {

			Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
			String day = c.get(Calendar.DAY_OF_MONTH) >= 10 ? Integer
					.toString(c.get(Calendar.DAY_OF_MONTH)) : "0"
					+ Integer.toString(c.get(Calendar.DAY_OF_MONTH));
			String month = c.get(Calendar.MONTH) >= 10 ? Integer.toString(c
					.get(Calendar.MONTH) + 1) : "0"
					+ Integer.toString(c.get(Calendar.MONTH) + 1);
			String year = Integer.toString(c.get(Calendar.YEAR));
			String currentdate = day + "-" + month + "-" + year;

			c = null;
			day = null;
			month = null;
			year = null;

			return currentdate;
		} catch (Exception e) {
			logger.logException("returnOrderCurrentDate Exception", e);
		}
		return null;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.order_detail_save_btn:
			saveOrderDetail();
			break;
		case R.id.order_detail_save_cancel:
			this.finish();
			break;

		default:
			break;
		}

	}

	private void saveOrderDetail() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					OrderDetailActivity.this);
			builder.setMessage(
					getResources().getString(R.string.alert_sales_booking))
					.setCancelable(false)
					.setPositiveButton(
							getResources().getString(R.string.common_yes),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {

									OrderDetailActivity.this
											.doSaveOrderDetail();

								}
							})
					.setNegativeButton(
							getResources().getString(R.string.common_no),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			builder.setTitle("Alert");
			AlertDialog alert = builder.create();
			alert.show();

		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("saveorder Detail", e);
		}
	}

	private List<ProductOrderBean> getOrderProductBean(OrderBean orderBean) {
		try {
			Criteria<ProductOrderBean> criteria = manager
					.generateCriteria(ProductOrderBean.class);
			criteria.addRestriction(ProductOrderBean.COL_ORDER_KEY,
					Operators.isEqual, orderBean.getOrderId());
			return criteria.execute();
		} catch (Exception e) {
			logger.logException("getOrderProductBean", e);
		}
		return null;
	}

	private void doSaveOrderDetail() {
		try {
			OrderBean orderBean;
			if (roverApp.getViewContext().containsKey(
					RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS)) {
				orderBean = (OrderBean) roverApp.getViewContext().get(
						RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS);
				List<ProductOrderBean> orderProductBeanList = getOrderProductBean(orderBean);
				for (ProductOrderBean productOrderBean : orderProductBeanList) {
					manager.deleteBean(productOrderBean);
				}

			} else {
				orderBean = new OrderBean();
				orderBean.setOrderId(String.valueOf(orderNumber));
			}

			orderBean.setAmount(orderBookingLine.getOrderAmount());
			orderBean.setCustomerCode(customerBean.getCode());
			orderBean.setDate(returnOrderCurrentDate());
			orderBean.setIsActive("Active");

			orderBean.setSalesType(String.valueOf(salesTypeSpinner
					.getItemAtPosition(salesTypeSpinner
							.getSelectedItemPosition())));

			orderBean.setStatus("Active");

			if (roverApp.getViewContext().containsKey(
					RoverConstants.CURRENT_PREVIOUS_ORDER_SUCESS)) {
				manager.updateBean(orderBean);
			} else {
				manager.saveBean(orderBean);
				appSetupBean.setLastOrder(String.valueOf(orderNumber));
				manager.updateBean(appSetupBean);
			}

			List<ProductBean> productBeanList = orderBookingLine
					.getProductBeanList();

			ProductOrderBean productOrderBean;
			ProductBean productBean;
			for (int i = 0; i < productBeanList.size(); i++) {
				productOrderBean = new ProductOrderBean();
				productBean = productBeanList.get(i);
				productOrderBean.setCode(productBean.getProductCode());
				productOrderBean.setDescription(productBean.getDescription());
				productOrderBean.setProductCode(productBean.getProductCode());
				productOrderBean.setQuantity(orderBookingLine
						.getProductQuantitylist().get(i));
				productOrderBean.setExecutionQuantity(orderBookingLine
						.getProductQuantitylist().get(i));
				productOrderBean.setUnitPrice(productBean.getUnitPrice());
				productOrderBean.setOrderkey(orderBean.getOrderId());
				productOrderBean.setProductkey(productBean.getProductCode());
				manager.saveBean(productOrderBean);
			}

			if (customerBean.getCreditLimit() == 0.0) {
				roverApp.showMessage(
						"Customer "
								+ customerBean.getCode()
								+ " have zero Credit Limit. \n Order Saved Sucessfully.",
						Toast.LENGTH_LONG);
			} else if (customerBean.getCreditLimit() < Double
					.parseDouble(orderBookingLine.getOrderAmount())) {
				roverApp.showMessage("Customer " + customerBean.getCode()
						+ " Credit Limit Exceed.\n Order Saved Sucessfully.",
						Toast.LENGTH_LONG);
			} else {
				roverApp.showMessage("Order Sucessfully Saved ",
						Toast.LENGTH_LONG);
			}
			
			roverApp.getViewContext().clear();

			this.finish();
			Intent intent = new Intent(this, CustomerRouteActivity.class);
			startActivity(intent);

		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("do save order Detail", e);
		}
	}
}
